package base.tree;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import app.util.StringUtil;

public class MenuTree {
	
	public static String root = "root";
	
	private Object children;
	
	private MenuTreeNode menuTreeNode;

	public MenuTreeNode getMenuTreeNode() {
		return menuTreeNode;
	}

	public void setMenuTreeNode(MenuTreeNode menuTreeNode) {
		this.menuTreeNode = menuTreeNode;
	}

	/**
	 * 建树
	 * @param dateList
	 * @param MenuTreeNodeNameKey
	 * @param treeParentKey
	 */
	public void buildTree(List<Map<String, Object>> dateList, String MenuTreeNodeNameKey, String treeParentKey){
		List<MenuTreeNode> MenuTreeNodeList = new ArrayList<MenuTreeNode>();
		for (int i = 0; dateList!=null && i < dateList.size(); i++) {
			Map<String, Object> map = dateList.get(i);
			MenuTreeNode menuTreeNode = new MenuTreeNode();
			menuTreeNode.setId(StringUtil.objectToStr(map.get("id")));
			menuTreeNode.setText(StringUtil.objectToStr(map.get(MenuTreeNodeNameKey)));
			menuTreeNode.setParentId(StringUtil.objectToStr(map.get(treeParentKey)));
			menuTreeNode.setMenuClass(StringUtil.objectToStr(map.get("menuClass")));
			menuTreeNode.setMenuCode(StringUtil.objectToStr(map.get("menuCode")));
			menuTreeNode.setLeaf(true);
			menuTreeNode.setIsUse((int)map.get("isUse"));
			MenuTreeNodeList.add(menuTreeNode);
		}
		
		List<MenuTreeNode> rootTrees = new ArrayList<MenuTreeNode>();
		
        for (MenuTreeNode MenuTreeNode : MenuTreeNodeList) {
            if(root.equals(MenuTreeNode.getParentId())){
            	rootTrees.add(MenuTreeNode);
            }
            for (MenuTreeNode t : MenuTreeNodeList) {
                if(t.getParentId().equals(MenuTreeNode.getId())){
                    if(MenuTreeNode.getChildren() == null){
                        List<MenuTreeNode> myChildrens = new ArrayList<MenuTreeNode>();
                        myChildrens.add(t);
                        MenuTreeNode.setLeaf(false);
                        MenuTreeNode.setChildren(myChildrens);
                    }else{
                    	MenuTreeNode.setLeaf(false);
                        MenuTreeNode.getChildren().add(t);
                    }
                }
            }
        }
        this.setChildren(rootTrees);
	}
	
	public Object getChildren() {
		return children;
	}

	public void setChildren(Object children) {
		this.children = children;
	}

}
